package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.service.UploadService;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWIPANZHIAPI;
import com.ruoyi.system.outto.goods.XINGSHIAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sdq
 * @Date 2022/7/5 10:27
 */
@Slf4j
@Service
public class XINGSHIAPIImpl implements XINGSHIAPI {
    @Resource
    private InfoImgMapper infoImgMapper;
    @Autowired
    private CommonApi commonApi;

    @Value("${desc.title}")
    private String descTitle;

    @Resource
    private UploadService uploadService;

    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;

    public static String getCover(Map<String, Object> params) {
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
            if (params.get(key) instanceof String && StringUtils.isNotEmpty((String) params.get(key))) {
                resut.append(key + "=" + params.get(key) + "&");
            }
            if (params.get(key) instanceof Boolean) {
                resut.append(key + "=" + params.get(key) + "&");
            }
            if (params.get(key) instanceof Long) {
                resut.append(key + "=" + params.get(key) + "&");
            }
            if (params.get(key) instanceof Integer && null != params.get(key)) {
                resut.append(key + "=" + params.get(key) + "&");
            }
        }
        return resut.toString();
    }
    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        Map<String, Object> action = new TreeMap<>();
        action.put("gameCode", "CYHXQZWZ");
        action.put("title", "【"+descTitle+"_"+ goodsInfoAndAttrValueDto.getId() + "】 " + goodsInfoAndAttrValueDto.getTitle());
        action.put("description", "【"+descTitle+"_"+ goodsInfoAndAttrValueDto.getId() + "】 " + goodsInfoAndAttrValueDto.getDes());
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), sa);
        action.put("price",bigDecimal);
        action.put("goodsImg", goodsInfoAndAttrValueDto.getTitleImg()==null?LCConstant.defaultImg:goodsInfoAndAttrValueDto.getTitleImg());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String images = "";
        if (CollectionUtils.isEmpty(infoImgs)){
            images =","+goodsInfoAndAttrValueDto.getTitleImg()==null?LCConstant.defaultImg:goodsInfoAndAttrValueDto.getTitleImg();
        }else {
            for(GoodsInfoImg infoImg1 : infoImgs){
                if(StringUtils.isNotEmpty(infoImg1.getImgUrl())){
                    images+=","+infoImg1.getImgUrl();
                }
            }
        }
        action.put("carouselImages",images.substring(1));
        action.put("detailsImages", images.substring(1));
        action.put("accountSource","ORIGINAL_USER");
        action.put("compensationService","SUPPORT");
        action.put("receivablesAccountType","BALANCE_AMOUNT");
        action.put("outGoodsNo",goodsInfoAndAttrValueDto.getId());
        String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
        if(regional.equals("安卓QQ")) {
            action.put("system", 1308l);
            action.put("district",1308l);
            action.put("server",1308l);
            action.put("professional",1308l);
        }else if(regional.equals("苹果QQ")){
            action.put("system", 1311l);
            action.put("district",1311l);
            action.put("server",1311l);
            action.put("professional",1311l);
        }else if(regional.equals("安卓微信")){
            action.put("system", 1310l);
            action.put("district",1310l);
            action.put("server",1310l);
            action.put("professional",1310l);
        }else{
            action.put("system", 1311l);
            action.put("district",1311l);
            action.put("server",1311l);
            action.put("professional",1311l);
        }
//        action.put("proxyId", sa.getOther());
        action.put("indulge", "true");
        Map<String, Object> params = new HashMap<>();
        params.put("proxyId", sa.getOther());
        params.put("timestamp", System.currentTimeMillis()+"");
        String proxyKey = sa.getSaleKey();
        String cover = MapUntils.getCover(action) + "timestamp=" + params.get("timestamp").toString() + "&key=" + proxyKey;
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        System.out.println(sign);
        Map<String,Object> linkMessage = new HashMap<>();
        linkMessage.put("linkPhone","15225225252");
        linkMessage.put("linkQq","15252525");
        action.put("linkMessage",linkMessage);
        Map<String,Object> accountMessage = new HashMap<>();
        accountMessage.put("gameAccount",System.currentTimeMillis());
        accountMessage.put("loginPassword","123456");
        action.put("accountMessage",accountMessage);
        params.put("action", action);
        params.put("sign", sign);
        return params;
    }
    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner);
        String paramsStr = JSONObject.toJSONString(params);
        log.info("醒狮新增请求参数={}", paramsStr);
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/saveOrUpdate", JSONObject.toJSONString(params), "application/json");
        log.info("醒狮新增返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String data = resultJson.getString("data");
        String msg = resultJson.getString("info");
        msg = MapUntils.unicodeToString(msg);
        Map<String, Object> result = new HashMap<>();
        if (!resultJson.getBoolean("success")) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if (artRecs.size() > 0) {
                artRecs.get(0).setOutid(JSONObject.parseObject(data).getString("goodsKeyNo"));
                artRecMapper.updateArtRec(artRecs.get(0));
            } else {
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setSaleCode(salePartner.getSaleName());
                artRecreq.setOutid(JSONObject.parseObject(data).getString("goodsKeyNo"));
                artRecMapper.insertArtRec(artRecreq);
            }
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", msg);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> action = new TreeMap<>();
        action.put("outGoodsNo", goodsInfoAndAttrValueDto.getId());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        action.put("goodsKeyNo",artRecs.get(0).getOutid());
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), salePartner.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), salePartner);
        action.put("price", bigDecimal);
        Map<String, Object> params = new HashMap<>();
        params.put("proxyId", salePartner.getOther());
        params.put("timestamp", System.currentTimeMillis()+"");
        String proxyKey = salePartner.getSaleKey();
        String cover = MapUntils.getCover(action) + "timestamp=" + params.get("timestamp").toString() + "&key=" + proxyKey;
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        System.out.println(sign);
        params.put("action", action);
        params.put("sign", sign);
        System.out.println(params);
        log.info("醒狮编辑请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/updateGoodsPrice", JSONObject.toJSONString(params), "application/json");
        log.info("醒狮编辑返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("info");
        msg = MapUntils.unicodeToString(msg);
        Map<String, Object> result = new HashMap<>();
        if (!resultJson.getBoolean("success")) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", msg);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> action = new TreeMap<>();
        action.put("outGoodsNo", goodsInfoAndAttrValueDto.getId());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        action.put("goodsKeyNo",artRecs.get(0).getOutid());
        Map<String, Object> params = new HashMap<>();
        params.put("proxyId", salePartner.getOther());
        params.put("timestamp", System.currentTimeMillis()+"");
        String proxyKey = salePartner.getSaleKey();
        String cover = getCover(action) + "timestamp=" + params.get("timestamp").toString() + "&key=" + proxyKey;
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        System.out.println(sign);
        params.put("action", action);
        params.put("sign", sign);
        System.out.println(params);
        log.info("醒狮删除请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/downStandGoods", JSONObject.toJSONString(params), "application/json");
        log.info("醒狮删除返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("info");
        msg = MapUntils.unicodeToString(msg);
        Map<String, Object> result = new HashMap<>();
        if (!resultJson.getBoolean("success")) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            artRecMapper.deleteArtRecById(artRecs.get(0).getId());
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", msg);
        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        Map<String, Object> action = new TreeMap<>();
        action.put("gameCode", "CYHXQZWZ");
        Map<String, Object> params = new HashMap<>();
        params.put("proxyId", "zuyoule");
        params.put("timestamp", System.currentTimeMillis()+"");
        String proxyKey = "pzds_open_api_sign_1E24BC82DC0E70C833A62759DB200EE0";
        String cover = getCover(action) + "timestamp=" + params.get("timestamp").toString() + "&key=" + proxyKey;
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        System.out.println(sign);
        params.put("action", action);
        params.put("sign", sign);
        System.out.println(params);
        String response = HttpUtils.sendPost("http://47.109.37.64:10021/third/properties", JSONObject.toJSONString(params), "application/json");
//        String response = getGames();
        System.out.println(response);
    }

    static String getGames(){
        Map<String, Object> action = new TreeMap<>();
        action.put("proxyId", "zuyoule");
        Map<String, Object> params = new HashMap<>();
        params.put("proxyId", "zuyoule");
        params.put("timestamp", System.currentTimeMillis()+"");
        String proxyKey = "pzds_open_api_sign_1E24BC82DC0E70C833A62759DB200EE0";
        String cover = getCover(action) + "timestamp=" + params.get("timestamp").toString() + "&key=" + proxyKey;
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        System.out.println(sign);
        params.put("action", action);
        params.put("sign", sign);
        System.out.println(params);
        String response = HttpUtils.sendPost("http://47.109.37.64:10021/third/cooperateGames", JSONObject.toJSONString(params), "application/json");
        return response;
    }

}
